//
//  LSZTabBarItem.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/12.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit

class LSZTabBarItem: UITabBarItem {
    
    override var badgeValue: String? {
        didSet{
            //  1. 直接去我们主窗口的根视图控制器
//            let tabBarController = UIApplication.sharedApplication().keyWindow?.rootViewController as? UITabBarController
//            2通过KVC
            let tabBarController = valueForKey("_target") as? UITabBarController
            
//            依次循环找出所需要的控件
            for tabbarChild in tabBarController!.tabBar.subviews {
                
                if tabbarChild.isKindOfClass(NSClassFromString("UITabBarButton")!){
                    for tabbarButtonChild in tabbarChild.subviews {
                        
                        if tabbarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                            
                            for badgeViewChild in tabbarButtonChild.subviews {
                                
                                if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!){
//                                统计类里有多少成员变量
                                    
                                    var count: UInt32 = 0
//                                    获取里面的成员列表
                                    let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground")!, &count)
                                    
                                    for i in 0..<count {
//                                        获取指定位置的成员
                                        let ivar = ivars[Int(i)]
//                                        获取成员名字
                                        
                                        let name = ivar_getName(ivar)
                                        let type = ivar_getTypeEncoding(ivar)
                                        
//                                        把获取的成员名字转成字符串
                                        let nameStr = String(CString: name, encoding: NSUTF8StringEncoding)
                                        let typeStr = String(CString: type , encoding: NSUTF8StringEncoding)
                                        
//                                        使用kvc方式给成员变量赋值
                                        if nameStr == "_image"{
                                            badgeViewChild.setValue(UIImage(named: "main_badge"), forKey: "_image")
                                        
                                    }
               
                            }
                        
                            }
                            
                        }
        
                    }
                    
                }
                
            }
            
        }
    }

  }
}